package com.atmilan.quartz.utils.product;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.StockAreaTempEnum;
import com.atmilan.quartz.model.dto.jky.JkyProductResDTO;
import com.atmilan.quartz.model.dto.jky.JkyProductSkuPriceResDTO;
import com.atmilan.quartz.model.dto.jky.JkyProductSkuResDTO;
import com.atmilan.quartz.model.entity.crmeb.*;
import com.atmilan.quartz.model.request.*;
import com.atmilan.quartz.service.IJkyContrastService;
import com.atmilan.quartz.service.IStoreProductDescriptionService;
import com.atmilan.quartz.utils.ProductUtil;
import com.atmilan.quartz.utils.jackyun.BaseRequestBizData;
import com.atmilan.quartz.utils.jackyun.JackyunOpenHttpUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.util.StringUtil;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 拉取商品源数据
 */

@Slf4j
@Service
public class JkyProductUtil {

    @Resource
    IStoreProductDescriptionService storeProductDescriptionService;
    @Resource
    IJkyContrastService jkyContrastService;
    @Resource
    ProductUtil productUtil;

    /**
     * @param @param  pageNow
     * @param @param  pageSize
     * @param @return
     * @param @throws Exception
     * @return InProductResDTO
     * @throws Exception 查询分页商品数据
     * @throws
     * @Description:
     * @author daigb
     */
    public static JkyProductResDTO selectJkyPage(Integer pageNow, Integer pageSize, String goodsNo, String startTime, String endTime, String skuStartTime, String skuEndTime) throws Exception {
        JkyProductResDTO jkyProductResDTO = null;
        try {
            JackyunGoodsRequest jackyunGoodsRequest = new JackyunGoodsRequest();
            jackyunGoodsRequest.setPageIndex(pageNow);
            jackyunGoodsRequest.setPageSize(pageSize);
            if (StringUtil.isNotEmpty(goodsNo)) {
                jackyunGoodsRequest.setGoodsNo(goodsNo);
            }
            if (StringUtil.isNotEmpty(startTime)) {
                jackyunGoodsRequest.setStartDateModifiedSku(startTime);
            }
            if (StringUtil.isNotEmpty(endTime)) {
                jackyunGoodsRequest.setEndDateModifiedSku(endTime);
            }
            if (StringUtil.isNotEmpty(skuStartTime)) {
                jackyunGoodsRequest.setStartDateModifiedSku(skuStartTime);
            }
            if (StringUtil.isNotEmpty(skuEndTime)) {
                jackyunGoodsRequest.setEndDateModifiedSku(skuEndTime);
            }
            String result = JackyunOpenHttpUtils.post("erp.storage.goodslist", "v1.0", jackyunGoodsRequest);
            ObjectMapper mapper = new ObjectMapper();
            jkyProductResDTO = mapper.readValue(result, JkyProductResDTO.class);
            // 临时处理
            // Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jkyProductResDTO;
    }

    /**
     * 分页获取批次仓库sku信息
     *
     * @param @param  goodsNo
     * @param @return
     * @param @throws Exception
     * @return JkyProductSkuResDTO
     * @throws
     * @Description:
     * @author daigb
     */
    public static JkyProductSkuResDTO pageJkyBatchSkus(Integer pageNow, Integer pageSize, String warehouseCode, Integer intervalOfHour, Date checkDate) throws Exception {
        JkyProductSkuResDTO jkyProductSkuResDTO = null;
        try {
            JackyunGoodsStockRequest jackyunGoodsRequest = new JackyunGoodsStockRequest();
            jackyunGoodsRequest.setPageIndex(pageNow);
            jackyunGoodsRequest.setPageSize(pageSize);
            jackyunGoodsRequest.setWarehouseCode(warehouseCode);
            if (null != intervalOfHour) {
                if (null == checkDate) checkDate = new Date();
                jackyunGoodsRequest.setGmtModifiedStart(DateUtil.format(DateUtil.offsetHour(checkDate, 0 - intervalOfHour), "yyyy-MM-dd HH:mm:ss"));
                jackyunGoodsRequest.setGmtModifiedEnd(DateUtil.format(checkDate, "yyyy-MM-dd HH:mm:ss"));
            }
            XxlJobHelper.log("业务请求参数:" + JSONObject.toJSONString(jackyunGoodsRequest));
            String result = JackyunOpenHttpUtils.post("erp.stockquantity.get", "v1.0", jackyunGoodsRequest);
            ObjectMapper mapper = new ObjectMapper();
            jkyProductSkuResDTO = mapper.readValue(result, JkyProductSkuResDTO.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e);
        }
        return jkyProductSkuResDTO;
    }

    /**
     * @param @param  goodsNo
     * @param @return
     * @param @throws Exception
     * @return List<GoodsStockQuantity>
     * @throws Exception 分页获取仓库sku信息
     * @throws
     * @Description:
     * @author daigb
     */
    public JkyProductSkuResDTO pageJkySkus(Integer pageNow, Integer pageSize, String warehouseCode, String skuBarcodes) throws Exception {
        JkyProductSkuResDTO jkyProductSkuResDTO = null;
        try {
            JackyunGoodsRequest jackyunGoodsRequest = new JackyunGoodsRequest();
            jackyunGoodsRequest.setPageIndex(pageNow);
            jackyunGoodsRequest.setPageSize(pageSize);
            jackyunGoodsRequest.setWarehouseCode(warehouseCode);
            if (StringUtils.isNotBlank(skuBarcodes)) {
                jackyunGoodsRequest.setSkuBarcode(skuBarcodes);
            }

            String result = JackyunOpenHttpUtils.post("erp.stockquantity.get", "v1.0", jackyunGoodsRequest);
            ObjectMapper mapper = new ObjectMapper();
            jkyProductSkuResDTO = mapper.readValue(result, JkyProductSkuResDTO.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jkyProductSkuResDTO;
    }

    /**
     * 获取商品sku价格
     *
     * @param @param  ids
     * @param @return
     * @param @throws Exception
     * @return InProductResDTO
     * @throws
     * @Description:
     * @author daigb
     */
    public JkyProductSkuPriceResDTO getJkySkuPrice(String skuBarcode, String goodsNo) throws Exception {
        JkyProductSkuPriceResDTO jkyProductSkuPriceResDTO = null;
        try {
            JackyunGoodsRequest jackyunGoodsRequest = new JackyunGoodsRequest();
            if (StringUtil.isNotEmpty(skuBarcode)) {
                jackyunGoodsRequest.setSkuBarcode(skuBarcode);
            }
            if (StringUtil.isNotEmpty(goodsNo)) {
                jackyunGoodsRequest.setGoodsNo(goodsNo);
            }
            String result = JackyunOpenHttpUtils.post("erp.pricelist.get", "v1.0", jackyunGoodsRequest);
            ObjectMapper mapper = new ObjectMapper();
            jkyProductSkuPriceResDTO = mapper.readValue(result, JkyProductSkuPriceResDTO.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jkyProductSkuPriceResDTO;
    }

    /**
     * @param @param  product
     * @param @param  values
     * @param @param  category
     * @param @param  markupRate
     * @param @throws Exception
     * @return 组装待创建商品
     * @return void
     * @throws
     * @Description:
     * @author daigb
     */
    public Map<String, Object> createJkySkus(StoreProduct product, List<StoreProductAttrValue> values, Category category, BigDecimal markupRate) throws Exception {
        Map<String, Object> map = null;
        try {
            map = new HashMap<>();
            List<BaseRequestBizData> goodsList = new ArrayList<>();
            List<BaseRequestBizData> jsonStrs = new ArrayList<BaseRequestBizData>();
            List<JackyunGoodsStockInRequest.StockInDetailView> stockInDetailViews = new ArrayList<>();
            JSONArray sliderImage = JSONArray.parseArray(product.getSliderImage());
            // 查询货品skuid
            Thread.sleep(1000);
            JkyProductResDTO jkyProductResDTO = selectJkyPage(0, 200, product.getId().toString(), null, null, null, null);

            // 组装吉客云商品信息
            int index = 0;
            for (StoreProductAttrValue value : values) {
                index++;
                // 查询商品是否有匹配到
                JkyContrast jkyContrast = compJkyNo(product, value, index);
                if (null == jkyContrast) {
                    continue;
                }
                // 商品和sku信息
                JackyunGoodsAddRequest goods = new JackyunGoodsAddRequest();
                goods.setGoodsName(product.getStoreName().replaceAll("&", ""));
                goods.setGoodsNo(jkyContrast.getGoodsNo());
                //goods.setGoodsAlias(product.getKeyword());
                goods.setGoodsAlias(product.getSeasonCode());
                goods.setCateCode(product.getCateId() + "");
                goods.setCateName(category.getName());
                goods.setBrandName(product.getBrandName().replaceAll("&", ""));
                goods.setUnitName(product.getUnitName());
                goods.setGoodsField7(product.getComposition());
                goods.setGoodsField4(product.getProductionPlace());
                goods.setGoodsField11(StockAreaTempEnum.getByTempId(product.getTempId()).getStockAreaName());
                goods.setGoodsField12(productUtil.getDeliveryTimeByTempId(product.getTempId(), product.getIsEurope(), product.getMerId(), product.getId()));
                goods.setGoodsField13(product.getSuppliersName());
                if (!value.getSuk().contains(";") && !StringUtil.isEmpty(product.getColorCode())) {
                    goods.setSkuName(product.getColorCode() + "," + value.getSuk());
                } else {
                    goods.setSkuName(value.getSuk().replace(";", ","));
                }
                goods.setOutSkuCode(value.getSourceSkuId());
                goods.setSkuBarcode(jkyContrast.getSkuNo());
                goods.setOwnerCode(String.valueOf(product.getId()));
                goods.setSkuNo(jkyContrast.getSkuNo());
                //goods.setSkuName(value.getSuk());
                goods.setMainBarcode(product.getKeyword()); // 公码
                goods.setMainGoodsUrl(product.getImage());
                goods.setSkuImageUrl(value.getImage());
                if (null != sliderImage) {
                    if (4 < sliderImage.size()) {
                        goods.setTopGoodsUrl(sliderImage.getString(1));
                        goods.setBelowGoodsUrl(sliderImage.getString(2));
                        goods.setLeftGoodsUrl(sliderImage.getString(3));
                        goods.setRightGoodsUrl(sliderImage.getString(4));
                    } else {
                        for (int i = 0; i < sliderImage.size(); i++) {
                            if (i == 0) {
                                goods.setTopGoodsUrl(sliderImage.getString(i));
                            } else if (i == 1) {
                                goods.setBelowGoodsUrl(sliderImage.getString(i));
                            } else if (i == 2) {
                                goods.setLeftGoodsUrl(sliderImage.getString(i));
                            } else if (i == 3) {
                                goods.setRightGoodsUrl(sliderImage.getString(i));
                            }
                        }
                    }
                }

                goods.setDescript("");
                goodsList.add(goods);

                // 价格
                BigDecimal price = value.getPrice().add(value.getPrice().multiply(markupRate.multiply(new BigDecimal("0.01"))).setScale(2, RoundingMode.HALF_UP));
                JackyunGoodsSkuAddRequest skuPrice = new JackyunGoodsSkuAddRequest();
                skuPrice.setSkuName(goods.getSkuName());
                skuPrice.setRetailPrice(price);
                skuPrice.setSkuWeight(value.getOtPrice()); // 原价往重量上赋值
                skuPrice.setSkuBarcode(jkyContrast.getSkuNo());
                // 匹配吉客云skuId
                List<JkyProductResDTO.Goods> jkyGoodsList = jkyProductResDTO.getResult().getDataResult().getGoods();
                for (JkyProductResDTO.Goods g : jkyGoodsList) {
                    if (null == g.getSkuCode()) {
                        continue;
                    }
                    if (g.getSkuCode().equals(goods.getSkuNo())) {
                        skuPrice.setSkuId(g.getSkuId());
                        break;
                    }
                }
                if (StringUtil.isEmpty(skuPrice.getSkuId())) {
                    // TODO 注意这个014单独处理的
                    // 占位
//                    skuPrice.setSkuId(jkyContrast.getSkuNo());
                    skuPrice.setSkuId(jkyContrast.getId().toString());
                }
                jsonStrs.add(skuPrice);

                // 库存
                JackyunGoodsStockInRequest.StockInDetailView stockInDetailView = new JackyunGoodsStockInRequest.StockInDetailView();
//                stockInDetailView.setOutSkuCode(jkyContrast.getSkuNo());
                //2023.6.9修改入库单的skucode
                stockInDetailView.setOutSkuCode(value.getSourceSkuId());
                stockInDetailView.setRelDetailId(0);
                stockInDetailView.setSkuCount(new BigDecimal(value.getStock()));
                stockInDetailView.setIsCertified("1");
                stockInDetailViews.add(stockInDetailView);
            }

            map.put("goodsList", goodsList);
            map.put("jsonStrs", jsonStrs);
            map.put("stockInDetailViews", stockInDetailViews);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 生成出库单
     *
     * @param @throws Exception
     * @return void
     * @throws
     * @Description:
     * @author daigb
     */
    public static void createJkyGoodsStockOut(List<JackyunGoodsStockOutRequest.StockOutDetailView> stockOutDetailViews) throws Exception {
        // 临时处理
        Thread.sleep(1000);
        JackyunGoodsStockOutRequest stock = new JackyunGoodsStockOutRequest();
        stock.setOutWarehouseCode("8f001");
        stock.setOutType(204);
        Long l = System.currentTimeMillis();
        stock.setRelDataId(l + "");
        stock.setApplyDepartName("daigb");
        stock.setApplyDate(new Date());
        stock.setOperator("daigb");
        stock.setSource("OPEN");

        stock.setStockOutDetailViews(stockOutDetailViews);

        String result = JackyunOpenHttpUtils.post("erp.stock.createandstockout", "v1.0", stock);
        log.info("--------------- 吉客云出库: {}", result);
        if (200 != JSONObject.parseObject(result).getInteger("code")) {
            log.info("--------------- 吉客云出库异常: {}", result);
        }
    }

    /**
     * 批量创建商品价格
     *
     * @param @param  goodsNo
     * @param @param  skuBarcode
     * @param @throws Exception
     * @return void
     * @throws
     * @Description:
     * @author daigb
     */
    public static void createJkyGoodsSku(List<BaseRequestBizData> jsonStrs) throws Exception {
        // 临时处理
        Thread.sleep(1000);
        String result = JackyunOpenHttpUtils.post("erp.goodsku.updatebyskubarcode", "v1.0", jsonStrs);
        log.info("--------------- 吉客云创建sku价格: {}", result);
        if (200 != JSONObject.parseObject(result).getInteger("code")) {
            log.info("--------------- 吉客云创建sku价格异常: {}", result);
        }
    }

    /**
     * 生成入库单
     *
     * @param @throws Exception
     * @return void
     * @throws
     * @Description:
     * @author daigb
     */
    public static void createJkyGoodsStockIn(List<JackyunGoodsStockInRequest.StockInDetailView> stockInDetailViews) throws Exception {
        // 临时处理
        Thread.sleep(1000);
        JackyunGoodsStockInRequest stock = new JackyunGoodsStockInRequest();
        stock.setApplyDepartCode("CP003");
        stock.setApplyCompanyCode("0001");
        stock.setInWarehouseCode("8f001");
        stock.setInType(104);
        stock.setRelDataId(System.currentTimeMillis() + "");
        stock.setApplyUserName("daigb");
        stock.setApplyDate(new Date());
        stock.setOperator("daigb");
        stock.setSource("OPEN");
        stock.setLogisticNo("SF888888888888");
        stock.setStockInDetailViews(stockInDetailViews);

        String result = JackyunOpenHttpUtils.post("erp.stock.createandstockin", "v1.0", stock);
        log.info("--------------- 吉客云入库: {}", result);
        if (200 != JSONObject.parseObject(result).getInteger("code")) {
            log.info("--------------- 吉客云入库异常: {}", result);
        }
    }

    /**
     * @param @param  goodsNo
     * @param @return
     * @param @throws Exception
     * @return JkyProductSkuResDTO
     * @throws Exception 单商品库存查询
     * @throws
     * @Description:
     * @author daigb
     */
    public static List<JkyProductSkuResDTO.GoodsStockQuantity> getJkySkus(String goodsNo) throws Exception {
        List<JkyProductSkuResDTO.GoodsStockQuantity> goodsStockQuantitys = null;
        try {
            // 临时处理
            Thread.sleep(1000);
            JackyunGoodsRequest jackyunGoodsRequest = new JackyunGoodsRequest();
            jackyunGoodsRequest.setPageIndex(0);
            jackyunGoodsRequest.setPageSize(200);
            jackyunGoodsRequest.setWarehouseCode("8f001");
            jackyunGoodsRequest.setGoodsNo(goodsNo);
            String result = JackyunOpenHttpUtils.post("erp.stockquantity.get", "v1.0", jackyunGoodsRequest);
            ObjectMapper mapper = new ObjectMapper();
            JkyProductSkuResDTO jkyProductSkuResDTO = mapper.readValue(result, JkyProductSkuResDTO.class);
            goodsStockQuantitys = jkyProductSkuResDTO.getResult().getDataResult().getGoodsStockQuantity();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return goodsStockQuantitys;
    }

    /**
     * @param @param  product
     * @param @param  values
     * @param @param  category
     * @param @param  markupRate
     * @param @throws Exception
     * @return 查询待出库商品
     * @return void
     * @throws
     * @Description:
     * @author daigb
     */
    public static List<JackyunGoodsStockOutRequest.StockOutDetailView> selectOutJkyGoods(String id) throws Exception {
        // 先查询商品sku信息, 将库存出库
        List<JackyunGoodsStockOutRequest.StockOutDetailView> stockOutDetailViews = null;
        try {
            stockOutDetailViews = new ArrayList<>();
            List<JkyProductSkuResDTO.GoodsStockQuantity> goodsStockQuantitys = getJkySkus(id);
            for (JkyProductSkuResDTO.GoodsStockQuantity stockQuantity : goodsStockQuantitys) {
                if (Integer.parseInt(stockQuantity.getCurrentQuantity()) > 0) {
                    JackyunGoodsStockOutRequest.StockOutDetailView stockOutDetailView = new JackyunGoodsStockOutRequest.StockOutDetailView();
                    stockOutDetailView.setSkuBarcode(stockQuantity.getSkuBarcode());
                    stockOutDetailView.setRelDetailId(0);
                    stockOutDetailView.setSkuCount(new BigDecimal(stockQuantity.getCurrentQuantity()));
                    stockOutDetailView.setIsCertified("1");
                    stockOutDetailViews.add(stockOutDetailView);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return stockOutDetailViews;
    }

    // 匹配吉客云货品编号
    private JkyContrast compJkyNo(StoreProduct product, StoreProductAttrValue value, Integer index) {
        String keyword = product.getKeyword();
        String color = product.getColorCode();
        String season = product.getSeasonCode();
        String[] suk = value.getSuk().split(",");
        String size = suk.length > 1 ? suk[1] : suk[0];
        List<JkyContrast> jkyContrasts;

        // IM匹配规则, 暂时弃用
//    	if(StringUtil.isEmpty(keyCode)) {
//    		return null;
//    	}
//    	keyCode = keyCode.substring(0, 8);
//
//		List<JkyContrast> jkyContrasts = jkyContrastService.list(Wrappers.<JkyContrast>lambdaQuery()
//            		.likeRight(JkyContrast :: getGoodsNo, keyCode)
//            		.eq(StringUtil.isNotEmpty(season), JkyContrast :: getSeasonCode, season)
//            		);
//		for(JkyContrast jkyContrast : jkyContrasts) {
//			String jkySku = jkyContrast.getSuk();
//			String[] jkySkus = jkySku.split(";");
//			String colorCode = jkySkus[0].split(" ")[0].replaceAll("[^\\d]+", "");
//			// 有色号
//			if(jkySkus.length > 1 && StringUtil.isNotEmpty(color)) {
//				if(!colorCode.equals(color)) {
//					continue;
//				}
//			}
//			// 匹配尺码
//			String[] sizes = jkySkus.length > 1 ? jkySkus[1].split("=") : jkySkus[0].split("=");
//			if(size.equals(sizes[0]) || size.equals(sizes[1])) {
//				// 新增库存
//				jkyContrastService.update(Wrappers.<JkyContrast>lambdaUpdate()
//						.eq(JkyContrast :: getId, jkyContrast.getId())
//						.set(JkyContrast :: getStock, jkyContrast.getStock() + value.getStock())
//						);
//				return jkyContrast;
//			}
//		}

        // 01-BELLETTINI店铺规则
        if (product.getIsEurope() == ProductTypeEnum.BELLETTINI.getCode()) {
            // 拆分本地编码与色号
            StoreProductDescription description = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery().eq(StoreProductDescription::getProductId, product.getId()));
            String key = "DESIGNER ID: ";
            String descriptionName = description.getDescription();
            if (!descriptionName.contains(key) || !keyword.contains(" ")) {
                return null;
            }
            String[] keyCodes = descriptionName.substring(descriptionName.indexOf(key), descriptionName.length()).replace(key, "").split(" ");
            String keyCode = keyCodes[0].substring(0, keyCodes[0].length() >= 8 ? 8 : keyCodes[0].length());
            if (keyCodes.length < 2) {
                return null;
            }
            String colorCode = keyCodes[1];

            jkyContrasts = jkyContrastService.list(Wrappers.<JkyContrast>lambdaQuery()
                    .likeRight(JkyContrast::getGoodsNo, keyCode)
            );

            return matchJkyColor(jkyContrasts, size, colorCode, value.getStock());
        } else if (product.getIsEurope() == ProductTypeEnum.UNIBUY.getCode() || product.getIsEurope() == ProductTypeEnum.UNIBUY1.getCode()) {
            // 后期注意是否被处理默认规格
            String[] sizeUnibuy = size.split(";");
            size = sizeUnibuy.length > 1 ? sizeUnibuy[1] : sizeUnibuy[0];

            String keyCode = null;
            String colorCode = null;
            String storeName = null;
            Matcher mZ = Pattern.compile(".*[a-zA-Z]+.*").matcher(keyword);
            Matcher mSS = Pattern.compile("[0-9]*").matcher(keyword.charAt(0) + "");
            Matcher mSZ = Pattern.compile("[a-zA-Z]*").matcher(keyword.charAt(0) + "");

            // 规则匹配
            if (keyword.contains("-")) {
                String[] codes = keyword.split("-");
                // 方案1: 以2中划线区分, 1编号, 3色号
                if (codes.length >= 3) {
                    keyCode = codes[0].substring(0, 8);
                    colorCode = codes[2];
                    // 方案2: 一个中划线前面是品名, 2只取数字为色号
                } else if (codes.length == 2) {
                    storeName = codes[0];
                    colorCode = codes[1].split("[^\\d]+")[0];
                }
            } else if (keyword.contains("_")) {
                String[] codes = keyword.split("_");
                // 方案6: 有两个下划线, 1是编号, 3是色号
                if (codes.length >= 3) {
                    keyCode = codes[0].substring(0, 8);
                    colorCode = codes[2];
                    // 方案5: 有一个下划线, 前面是编号, 后面三位是色号
                } else if (codes.length == 2 && codes[0].length() > 7 && codes[0].length() > 2) {
                    keyCode = codes[0].substring(0, 8);
                    colorCode = codes[1].substring(codes[1].length() - 3, codes[1].length());
                }
            } else if (keyword.contains(" ")) {
                String[] codes = keyword.split(" ");
                // 方案8: 有空格, 前面编号, 后面色号
                keyCode = codes[0].substring(0, 8);
                colorCode = codes[1];
            } else if (!mZ.matches() && keyword.length() > 10) {
                // 方案4: 全数字类型, 前八位是编号, 后三位是色号
                keyCode = keyword.substring(0, 8);
                colorCode = keyword.substring(keyword.length() - 3, keyword.length());
            } else if (mZ.matches()) {
                // 方案3: 没有中划线, 数字打头中间有英文, 英文前面为编号, 后面是色号
                if (mSS.matches()) {
                    String[] codes = keyword.split("[^\\d]+");
                    keyCode = codes[0].substring(0, 8);
                    colorCode = codes[1];
                    // 方案7: 英文打头, 英文是品名, 数字是色号
                } else if (mSZ.matches()) {
                    Pattern p = Pattern.compile("[a-zA-Z]+|\\d+");
                    Matcher m = p.matcher(keyword);
                    ArrayList<String> allMatches = new ArrayList<>();
                    while (m.find()) {
                        allMatches.add(m.group());
                    }
                    if (1 < allMatches.size()) {
                        storeName = allMatches.get(0);
                        colorCode = allMatches.get(1);
                    }
                }
            }

            LambdaQueryWrapper<JkyContrast> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            if (StringUtil.isNotEmpty(keyCode)) {
                lambdaQueryWrapper.likeRight(JkyContrast::getGoodsNo, keyCode);
            } else if (StringUtil.isNotEmpty(storeName)) {
                lambdaQueryWrapper.like(JkyContrast::getGoodsName, storeName);
            }
            jkyContrasts = jkyContrastService.list(lambdaQueryWrapper);

            return matchJkyColor(jkyContrasts, size, colorCode, value.getStock());
        } else if (product.getIsEurope() == ProductTypeEnum.CAROTTA.getCode()) {
            // 拆分本地编码与色号
            String[] codes = keyword.split("[^\\d]+");
            if (codes.length < 2) {
                return null;
            }
            String keyCode = codes[0].substring(0, 8);
            String colorCode = codes[1];

            jkyContrasts = jkyContrastService.list(Wrappers.<JkyContrast>lambdaQuery()
                    .likeRight(JkyContrast::getGoodsNo, keyCode)
            );
            return matchJkyColor(jkyContrasts, size, colorCode, value.getStock());
        } else if (product.getIsEurope() == ProductTypeEnum.COLTORTI.getCode() || Objects.equals(product.getIsEurope(), ProductTypeEnum.GB.getCode()) || Objects.equals(product.getIsEurope(), ProductTypeEnum.IM.getCode()) || Objects.equals(product.getIsEurope(), ProductTypeEnum.JKY.getCode())) {
            JkyContrast jkyContrast = new JkyContrast();
            jkyContrast.setGoodsName(product.getStoreName());
            jkyContrast.setGoodsNo(product.getKeyword() + "-" + product.getId());
            jkyContrast.setSeasonCode(product.getSeasonCode());
            if (StringUtils.isNotBlank(value.getSelfSourceSkuId())) {
                jkyContrast.setSkuNo(value.getSelfSourceSkuId());
            } else {
                jkyContrast.setSkuNo(value.getSourceSkuId().split("-")[0]);
            }
            jkyContrast.setId(Long.parseLong(product.getId() + "" + index));
            return jkyContrast;
        }

        return null;
    }

    private JkyContrast matchJkyColor(List<JkyContrast> jkyContrasts, String size, String colorCode, Integer stock) {
        for (JkyContrast jkyContrast : jkyContrasts) {
            // 拆分吉客云色号与尺码
            String jkySku = jkyContrast.getSuk();
            String[] jkySkus = jkySku.split(";");
            String jkyColorCode = jkySkus[0].split(" ")[0].replaceAll("[^\\d]+", "");
            // 匹配尺码
            String[] sizes = jkySkus.length > 1 ? jkySkus[1].split("=") : jkySkus[0].split("=");
            boolean sizeType = false;
            if (sizes.length < 2) {
                sizeType = size.equals(sizes[0]);
            } else {
                sizeType = size.equals(sizes[0]) || size.equals(sizes[1]);
            }

            if (jkyColorCode.equals(colorCode) && sizeType) {
                // 新增库存
                jkyContrastService.update(Wrappers.<JkyContrast>lambdaUpdate()
                        .eq(JkyContrast::getId, jkyContrast.getId())
                        .set(JkyContrast::getStock, jkyContrast.getStock() + stock)
                );
                jkyContrast.setId(Long.parseLong(jkyContrast.getSkuNo()));
                return jkyContrast;
            }
        }

        return null;
    }

}
